﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace AB.Common
{
    /// <summary>
    /// Unicode帮助类
    /// </summary>
    public static class UniCodeHelper
    {
        /// <summary>  
        /// 字符串转为UniCode字符串  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <returns>UniCode字符串</returns>  
        public static string StringToUnicode(this string str)
        {
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    strResult.Append("\\u");
                    strResult.Append(((int)str[i]).ToString("x"));
                }
            }
            return strResult.ToString();
        }
        /// <summary>  
        /// Unicode字符串转为正常字符串  
        /// </summary>  
        /// <param name="str">Unicode字符串</param>  
        /// <returns>字符串</returns>  
        public static string UnicodeToString(this string str)
        {
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                string[] strlist = str.Replace("\\", "").Split('u');
                try
                {
                    for (int i = 1; i < strlist.Length; i++)
                    {
                        int charCode = Convert.ToInt32(strlist[i], 16);
                        strResult.Append((char)charCode);
                    }
                }
                catch (FormatException)
                {
                    return Regex.Unescape(str);
                }
            }
            return strResult.ToString();
        }
    }
}
